package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.Hops;

public class HopsPresenter extends AbstractPresenter<Hops> {
	final String SINGLEITEM = "hops";
	final String MULTIITEM = "hopss";
	
	public ArrayList<Hops> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public Hops tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public Hops createItemFromJSONObject(JSONObject jsonObject){
		Hops item = new Hops();
		try{
			item.setHopAlphaAcid(jsonObject.getDouble("hopAA"));
			item.setHopBagWeight(jsonObject.getDouble("hopBagLbs"));
			item.setHopCost(jsonObject.getDouble("hopCost"));
			item.setHopID(jsonObject.getInt("hid"));
			item.setHopMinimum(jsonObject.getDouble("hopMinimum"));
			item.setHopName(jsonObject.getString("hopName"));
			item.setHopOnHand(jsonObject.getDouble("hopOnHand"));
			item.setHopOnOrder(jsonObject.getDouble("hopOnOrder"));
			item.setHopSpoken(jsonObject.getDouble("hopSpoken"));
			item.setWholeHop(jsonObject.getBoolean("hopWhole"));
			
			final StockCodePresenter presenter = new StockCodePresenter();
			JSONObject jsonSC = jsonObject.getJSONObject("stockCode");
			item.setStockCode(presenter.createItemFromJSONObject(jsonSC));
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(Hops item){
		try{
			JSONObject json = new JSONObject();
			json.put("hopAA", item.getHopAlphaAcid());
			json.put("hopBagLbs", item.getHopBagWeight());
			json.put("hopCost", item.getHopCost());
			json.put("hid", item.getHopID());
			json.put("hopMinimum", item.getHopMinimum());
			json.put("hopName", item.getHopName());
			json.put("hopOnHand", item.getHopOnHand());
			json.put("hopOnOrder", item.getHopOnOrder());
			json.put("hopSpoken", item.getHopSpoken());
			json.put("hopWhole", item.isWholeHop());
			
			if(item.getStockCode()!=null){
				final StockCodePresenter presenter = new StockCodePresenter();
				json.put("stockCode", presenter.createJSON(item.getStockCode()));
			} else {
				json.put("stockCode", JSONObject.NULL);
			}

			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Hops getEmptyEntity(){
		Hops entity = new Hops();
		return entity;
	}
}
